//
//  SurveyerLoaderViewController.m
//  Surveyer
//
//  Created by Qikun Guo on 13-7-27.
//  Copyright (c) 2013年 Tim. All rights reserved.
//

#import "SurveyerLoaderViewController.h"
#import "DesignViewController.h"
#import "SurveyViewController.h"
#import "ResultViewController.h"
#import "ColorDef.h"
#import "Flurry.h"

@interface SurveyerLoaderViewController ()

@end

@implementation SurveyerLoaderViewController
@synthesize vc, dismissBlock;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self.tableView selector:@selector(reloadData) name:SurveyerStoreUpdateNotification object:nil];
        [[SurveyerStore defaultStore] sort];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (!strTitle)
        strTitle = [[SurveyerStore defaultStore] title];
    if ([strTitle isEqualToString:@"Design"])
    {
        self.navigationController.navigationBar.backgroundColor = DESIGN_BKG_COLOR;
        self.navigationItem.title = NSLocalizedString(@"Design", nil);
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showAlertView)];
    }
    else if ([strTitle isEqualToString:@"Survey"])
    {
        self.navigationController.navigationBar.backgroundColor = SURVEY_BKG_COLOR;
        self.navigationItem.title = NSLocalizedString(@"Survey", nil);
    }
    else if ([strTitle isEqualToString:@"Result"])
    {
        self.navigationController.navigationBar.backgroundColor = RESULT_BKG_COLOR;
        self.navigationItem.title = NSLocalizedString(@"Result", nil);
    }
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismiss)];
    
    [Flurry logAllPageViews:self.navigationController];
    
    formatter = [[NSDateFormatter alloc] init];
    formatter.dateStyle=NSDateFormatterMediumStyle;
    formatter.timeStyle=NSDateFormatterNoStyle;
    [formatter setLocale:[NSLocale currentLocale]];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillDisappear:(BOOL)animated
{
    [[SurveyerStore defaultStore] saveChanges];
}

#pragma mark - tableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
        return [[[SurveyerStore defaultStore] allSurvey] count];
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ([strTitle isEqualToString:@"Design"])
        return 2;
    return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0)
        return NSLocalizedString(@"Existing files", @"section name1");
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    if (indexPath.section == 0)
    {
        /*
        if ([SurveyerStore defaultStore].allSurvey.count == 0)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.textLabel.text = NSLocalizedString(@"No Survey Available", nil);
        }
         
        else
         */
        {
            Survey *s = [[[SurveyerStore defaultStore] allSurvey] objectAtIndex:indexPath.row];
            cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
            if (cell == nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
            }
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:s.modifiedDate];
            [cell.textLabel setText:s.title];
            [cell.detailTextLabel setText:[formatter stringFromDate:date]];
        }
    }
    else
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        cell.textLabel.text = NSLocalizedString(@"Start With Template", @"section name2");
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView beginUpdates];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [[SurveyerStore defaultStore] removeSurvey:[[[SurveyerStore defaultStore] allSurvey] objectAtIndex:indexPath.row]];
        [tableView endUpdates];
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && [SurveyerStore defaultStore].allSurvey.count != 0)
        return YES;
    return NO;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Survey *s;
    if (indexPath.section == 0 && [SurveyerStore defaultStore].allSurvey.count != 0)
    {
        s = [[[SurveyerStore defaultStore] allSurvey] objectAtIndex:indexPath.row];
    }
    else
    {
        s = [[SurveyerStore defaultStore] templateSurvey];
        if (!s)
        {
            UIAlertView *av = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Name Conflict", nil) message:NSLocalizedString(@"A survey with the same name already exists.", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil];
            [av show];
            return;
        }
    }
    NSDate *date = [NSDate date];
    [s setModifiedDate:[date timeIntervalSince1970]];
    [self initVC];
    //set value for key
    [vc setValue:s forKey:@"currentSurvey"];
    [SurveyerStore defaultStore].latestSurvey = s;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - other methods
- (void)dismiss
{
    [[self navigationController] dismissViewControllerAnimated:YES completion:nil];
}

- (void)showAlertView
{
    UIAlertView *theAlertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Title of the survey", @"title of new button->alert view") message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Enter", nil), nil];
    theAlertView.alertViewStyle = UIAlertViewStylePlainTextInput;
    [theAlertView show];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    NSString *input = [alertView textFieldAtIndex:0].text;
    if (![input  isEqual: @""] && buttonIndex == 1)
    {
        Survey *s = [[SurveyerStore defaultStore] createSurveyWithTitle:input];
        if (!s)
        {
            UIAlertView *av = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Name Conflict", nil) message:NSLocalizedString(@"A survey with the same name already exists.", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil];
            [av show];
        }
        else
        {
            DesignViewController *dvc = [[DesignViewController alloc] init];
            [SurveyerStore defaultStore].latestSurvey = s;
            dvc.currentSurvey = s;
            [self.navigationController pushViewController:dvc animated:YES];
        }
    }
}

- (void)initVC
{
    if ([strTitle isEqualToString:@"Design"])
    {
        vc = [[DesignViewController alloc] init];
    }
    else if ([strTitle isEqualToString:@"Survey"])
    {
        vc = [[SurveyViewController alloc] init];
    }
    else
    {
        vc = [[ResultViewController alloc] init];
    }
}
@end